package org.company.earth.apache;

import java.util.Date;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.validator.routines.AbstractNumberValidator;
import org.apache.commons.validator.routines.CodeValidator;
import org.apache.commons.validator.routines.DateValidator;
import org.apache.commons.validator.routines.DoubleValidator;
import org.apache.commons.validator.routines.IntegerValidator;
import org.apache.commons.validator.routines.checkdigit.CheckDigit;


public class ValidatorUtil {
    
    private static DateValidator dateValidator = DateValidator.getInstance();
    
    private static CodeValidator getCodeValidator(String regExp,int min,int max,CheckDigit checkdigit) {
        return new CodeValidator(regExp,min,max,checkdigit);
    }
    
    public static AbstractNumberValidator getNumberValidator(Number value) {
        if(value instanceof Integer) {
            return IntegerValidator.getInstance();
        } else if(value instanceof Double) {
            return DoubleValidator.getInstance();
        }
        return null;
    }
    
    /**
     * 校验日期格式
     * @param dateStr
     * @param pattern
     * @return
     */
    public static Date validatorDate(String dateStr,String pattern) {
        return dateValidator.validate(dateStr, pattern);
    }
    
    /**
     * 字符串日期格式校验
     * @param dateStr
     * @param pattern
     * @return
     */
    public static boolean isValideDate(String dateStr,String pattern) {
        return dateValidator.isValid(dateStr, pattern);
    }
    
    public static Boolean isInRange(Number value,Number min,Number max) {
        return getNumberValidator(value).isInRange(value, min, max);
    }
    
    public static Boolean max(Number value,Number max) {
        return getNumberValidator(value).maxValue(value, max);
    }
    
    public static Boolean min(Number value,Number max) {
        return getNumberValidator(value).minValue(value, max);
    }
    
    private static Boolean isValid(String value,String regExp,int min,int max,CheckDigit checkdigit) {
        return getCodeValidator(regExp,min,max,checkdigit).isValid(value);
    }
    
    public static Boolean maxLength(String value,int max) {
        return isValid(value,null,-1,max,null);
    }
    
    public static Boolean minLength(String value,int min) {
        return isValid(value,null,min,-1,null);
    }
    
    public static Boolean length(String value,int min,int max) {
        return isValid(value,null,min,max,null);
    }
    
    /**
     * 是否是纯数字，(不包括小数点)
     * @param value
     * @return
     */
    public static boolean isDigit(String value) {
        return NumberUtils.isDigits(value);
    }
    
    /**
     * 校验是否是合法的数字
     * @param value
     * @return
     */
    public static boolean isNumber(String value) {
        return NumberUtils.isNumber(value);
    }
}
